﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.MemoryMappedFiles;

namespace InCom.Core.TerminalSend.MappedFile
{
    /// <summary>
    /// 用于文件映射的字符串
    /// </summary>
    public class MString
    {
        protected string val = string.Empty;

        /// <summary>
        /// 当前字符串字节最大长度 
        /// </summary>
        long curstringoffset = 0;
        /// <summary>
        /// 数据值 写入字符串长度超过系统分析长度值 MaxLength 时,字符串会被截断
        /// </summary>
        public string Value
        {
            get
            {
                long len = 0;
                //写入长度
                Access.Read<long>((long)(Offset - 8), out len);
                val = System.Text.Encoding.Unicode.GetString(MappedFileExtension.Read(Access, (int)Offset, len));
                return val;
            }
            set
            {
                if (val != value)
                {
                    val = value;
                    //设置值
                    byte[] strs=System.Text.Encoding.Unicode.GetBytes(val);
                    if (strs.Length > FileMaxLength-8)
                    {
                        //超过长度则截断.
                        byte[] reArr = new byte[FileMaxLength-8];
                        Buffer.BlockCopy(strs, 0, reArr, 0, reArr.Length);
                        strs = reArr;
                    }
                    curstringoffset = MappedFileExtension.Write(Access, strs, Offset);
                    long len=((long)strs.Length);
                    //写入长度
                    Access.Write<long>((long)(Offset - 8), ref len);
                }
            }
        }

       
        /// <summary>
        /// 创建一个新的基于内存文件的int
        /// </summary>
        /// <param name="offset">偏移量</param>
        /// <param name="access">映射对像</param>
        /// <param name="maxLength">最大字符串长度,一次性分配后不能修改,默认512个字符</param>
        public MString(long offset, MemoryMappedViewAccessor access, int maxLength = 512)
        {
            Access = access;
            //8字节长度描述
            Offset = 8+offset;
            MaxLength = maxLength;
        }



        /// <summary>
        /// 视图
        /// </summary>
        protected MemoryMappedViewAccessor Access { get; set; }

        /// <summary>
        /// 字符串最大可操作的内存长度  8字节长度描述
        /// </summary> 
        public int FileMaxLength { get { return MaxLength * 3+8; } }

        /// <summary>
        /// 最大字符串长度,一次性分配后不能修改,默认512个字符
        /// </summary>
        public int MaxLength { get; protected set; }

        /// <summary>
        /// 基于文件映射的依稀量
        /// </summary>
        public long Offset { get; protected set; }
    }
}
